package sort;

/**
 * 时间复杂度：O(N*logN)
 * 空间复杂度：O(N)
 * 稳定性：稳定
 */
public class MergeSort implements ISort{
    @Override
    public void sort(int[] array) {
        mergeSort(array,0,array.length - 1);
    }

    private void mergeSort(int[] array, int left, int right) {
        if(left >= right) {
            return;
        }
        int mid = (left + right) / 2;
        mergeSort(array,left,mid);
        mergeSort(array,mid+1,right);
        merge(array,left,mid,right);
    }

    public void sortNor(int[] array) {
        int gap = 1;
        while (gap < array.length) {
            for (int i = 0; i < array.length; i += gap) {
                int left = i;
                int mid = left + gap - 1;
                int right = mid + gap;
                if(right >= array.length) {
                    right = array.length - 1;
                }
                if(mid >= array.length) {
                    mid = array.length - 1;
                }
                merge(array,left,mid,right);

            }
            gap *= 2;
        }
    }

    private void merge(int[] array, int left, int mid, int right) {
        int s1 = left;
        int e1 = mid;
        int s2 = mid + 1;
        int e2 = right;
        int[] newArr = new int[right - left + 1];
        int k = 0;
        while (s1 <= e1 && s2 <= e2) {
            if(array[s1] < array[s2]) {
                newArr[k++] = array[s1++];
            }else {
                newArr[k++] = array[s2++];
            }
        }
        while (s1 <= e1) {
            newArr[k++] = array[s1++];
        }
        while (s2 <= e2) {
            newArr[k++] = array[s2++];
        }
        for(int i = left; i <= right; i++) {
            array[i] = newArr[i - left];
        }

    }
}
